<template>
	<el-dialog v-model="dialogVisible" title="图片上传" @close="onClose" :close-on-click-modal="false">
		<el-form :model="data.form" :rules="rules" ref="ruleFormRef">
			<el-form-item label="图片名称" :label-width="formLabelWidth" prop="name"><el-input v-model="data.form.name" placeholder="图片名称" /></el-form-item>
			<el-upload 
			:on-change="beforeAvatarUpload" 
			ref="uploadRef" 
			:on-exceed='onExceed'
			action="/img/add" 
			:limit='1' 
			:auto-upload="false" 
			:data="data.form" 
			:http-request="httpRequest">
				<template #trigger>
					<el-button type="primary">选择图片</el-button>
				</template>
				<template #tip>
					<div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
				</template>
			</el-upload>
		</el-form>
		<!-- role_name,user_code,user_name,password,phone,email,qq,note,role_id -->
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="dialogVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import md5 from 'js-md5';
import type { FormInstance,UploadRequestOptions } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { UploadProps } from 'element-plus'
import {ref} from 'vue'
//请求
const { proxy } = getCurrentInstance();
import { getCurrentInstance} from 'vue';
//dialogSend hook
import hook from '@/hooks/useDialogSend';
const {open,data,ruleFormRef,formLabelWidth,dialogVisible} = hook;
const emits = defineEmits(['closeDialog'])
defineExpose({ open });

// title, type, keyword, result, importance, keywordRadio
const rules = {
	name: [{ required: true, message: '请输入题目', trigger: 'blur' }]
};


import type { UploadInstance } from 'element-plus'
const uploadRef = ref<UploadInstance>()
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
		// let bool = !!data.form.id
		// let url = bool?'/img/update':'/img/add'
		uploadRef.value!.submit()
    } else {
      console.log('error submit!', fields)
    }
  })
}

function httpRequest(params: UploadRequestOptions){
	console.log(6666666);
	// 上传新文件时，将进度条值置为零
	const file = params.file
	const forms = new FormData() // 实例化一个formData，用来做文件上传
	forms.append('file', file)
	forms.append('name', params.data.name)
	proxy.$post('/img/add',forms).then(res =>{
		console.log(res);
		if(res.code===200){
			ElMessage({
			  message: res.msg,
			  type: 'success',
			})
			onClose(true)
		}
	})

}

function onClose(bool){
	emits('closeDialog',bool)
	dialogVisible.value = false
	data.form = {}
}
function beforeAvatarUpload(a,b){
	console.log(a,b);
	return false
}
function onExceed(a,b){
	console.log(a,b);
	ElMessage('只允许上传一个图片')
}
</script>

<style scoped lang="less"></style>
